#include "ota_runner.h"
#include "ota_http.h"
#include "thirdparty/log.c/log.h"
#include <unistd.h>
#include <sys/reboot.h>

#define ONE_DAY 86400
#define ONE_WEEK 604800

static Version current_version = CURRENT_VERSION;

static int running = 1;

/**
 * @brief 比较新旧两个版本，返回是否需要省级
 *
 * @param new
 * @param old
 * @return int 0需要 -1不需要
 */
static int ota_runner_compareVersion(Version *newVer, Version *oldVer)
{
    if (newVer->major > oldVer->major)
    {
        return 0;
    }
    else if (newVer->major == oldVer->major)
    {
        if (newVer->minor > oldVer->minor)
        {
            return 0;
        }
        else if (newVer->minor == oldVer->minor)
        {
            if (newVer->patch > oldVer->patch)
            {
                return 0;
            }
        }
    }
    return -1;
}

void ota_runner_run()
{
    Version ver;

    while (running)
    {
        // 获取远端版本号
        if (ota_http_getVersion(&ver) < 0)
        {
            sleep(ONE_DAY);
            continue;
        }

        if (ota_runner_compareVersion(&ver, &current_version) < 0)
        {
            log_info("Do not need to update");
            sleep(ONE_WEEK);
            continue;
        }

        if (ota_http_getFirmware(FIRMWARE_FILENAME) < 0) {
            log_warn("Download firmware failed");
            sleep(ONE_DAY);
            continue;
        }
        
        // 更新成功，重启
        reboot(RB_AUTOBOOT);
    }
}